﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Data.Objects;
using System.Printing;
using Rdl.Engine;
using System.IO;
using Microsoft.Win32;

namespace PrintOrders
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private SalesManagerEntities _sme = new SalesManagerEntities();
        private CollectionViewSource _packagesViewSource;

        public MainWindow()
        {
            List<string> s = new List<string>();
            InitializeComponent();
        }

        private void chkCheckAll_Click(object sender, RoutedEventArgs e)
        {
            ListCollectionView packages = (ListCollectionView)gridOrders.ItemsSource;
            foreach (tblPackage package in packages)
            {
                package.Selected = (bool)chkCheckAll.IsChecked;
            }
        }

        private static readonly DependencyProperty HasPackagesSelected =
            DependencyProperty.Register("PackagesSelected", typeof(bool), typeof(MainWindow));
        protected bool PackagesSelected
        {
            get { return (bool)GetValue(HasPackagesSelected); }
        }

        private void btnLoad_Click(object sender, RoutedEventArgs e)
        {
            SqlConnection conn = (SqlConnection)((System.Data.EntityClient.EntityConnection)_sme.Connection).StoreConnection;
            if (conn.State != System.Data.ConnectionState.Open)
                conn.Open();
            SqlCommand cmm = conn.CreateCommand();

            SqlDataReader rdr;
            try
            {
                Cursor = Cursors.Wait;
                cmm.CommandText = "exec spSelectPackagesForPrinting @OwnerID, @LocationID";
                cmm.CommandTimeout = 1200;
                cmm.Parameters.Add(new SqlParameter("@OwnerID", cmbOwner.SelectedValue));
                cmm.Parameters.Add(new SqlParameter("@LocationID", cmbLocation.SelectedValue));
                rdr = cmm.ExecuteReader();
                Cursor = Cursors.Arrow;
            }
            catch ( Exception err )
            {
                Cursor = Cursors.Arrow;
                MessageBox.Show("Error selecting packages for printing\n" + err.Message);
                return;
            }

            _packagesViewSource.Source = _sme.Translate<tblPackage>(rdr, "SalesManagerEntities.tblPackage", MergeOption.AppendOnly).ToArray();
            rdr.NextResult();
            _sme.Translate<tblInventoryTransaction>(rdr, "SalesManagerEntities.tblInventoryTransaction", MergeOption.AppendOnly).Count();
            rdr.NextResult();
            _sme.Translate<tblInventory>(rdr, "SalesManagerEntities.tblInventory", MergeOption.AppendOnly).Count();
            rdr.NextResult();
            _sme.Translate<tblProduct>(rdr, "SalesManagerEntities.tblProduct", MergeOption.AppendOnly).Count();
            rdr.NextResult();
            _sme.Translate<tblPerson>(rdr, "SalesManagerEntities.tblPerson", MergeOption.AppendOnly).Count();
            rdr.NextResult();
            _sme.Translate<tblAddress>(rdr, "SalesManagerEntities.tblAddress", MergeOption.AppendOnly).Count();

            rdr.Close();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            CollectionViewSource ownersViewSource = (CollectionViewSource)FindResource("Owners");
            ownersViewSource.Source = from c in _sme.tblOwner select c;
            CollectionViewSource locationsViewSource = (CollectionViewSource)FindResource("Locations");
            locationsViewSource.Source = from c in _sme.tblLocation
                                         where c.LocationTypeCode == "W"
                                         select c;

            _packagesViewSource = (CollectionViewSource)FindResource("Packages");
            List<string> printQueueNames = new List<string>();

            LocalPrintServer ps = new LocalPrintServer();
            foreach (PrintQueue q in ps.GetPrintQueues(new EnumeratedPrintQueueTypes[] { EnumeratedPrintQueueTypes.Local, EnumeratedPrintQueueTypes.Connections }))
                printQueueNames.Add(q.FullName);

            printQueueNames.Sort();

            ((CollectionViewSource)FindResource("PrintSummaryTo")).Source = printQueueNames;
            ((CollectionViewSource)FindResource("PrintPickListTo")).Source = printQueueNames;
            ((CollectionViewSource)FindResource("PrintPackingSlipsTo")).Source = printQueueNames;

            RegistryKey rkey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\SawikiSoft\OpenSalesManager");
            if (rkey != null)
            {
                if (rkey.GetValue("PrintSummaryTo") != null)
                    cmbPrintSummaryTo.SelectedItem = rkey.GetValue("PrintSummaryTo");
                else
                    cmbPrintPackingSlipsTo.SelectedItem = LocalPrintServer.GetDefaultPrintQueue().FullName;
                if (rkey.GetValue("PrintPickListTo") != null)
                    cmbPrintPickListTo.SelectedItem = rkey.GetValue("PrintPickListTo");
                else
                    cmbPrintPickListTo.SelectedItem = LocalPrintServer.GetDefaultPrintQueue().FullName;
                if (rkey.GetValue("PrintPackingSlipsTo") != null)
                    cmbPrintPackingSlipsTo.SelectedItem = rkey.GetValue("PrintPackingSlipsTo");
                else
                    cmbPrintPackingSlipsTo.SelectedItem = LocalPrintServer.GetDefaultPrintQueue().FullName;
            }

            cmbPrintSummaryTo.SelectionChanged += new SelectionChangedEventHandler(cmbPrintSummaryTo_SelectionChanged);
            cmbPrintPickListTo.SelectionChanged += new SelectionChangedEventHandler(cmbPrintPickListTo_SelectionChanged);
            cmbPrintPackingSlipsTo.SelectionChanged += new SelectionChangedEventHandler(cmbPrintPackingSlipsTo_SelectionChanged);
        }

        private void btnProcess_Click(object sender, RoutedEventArgs e)
        {
            // get a list of the selected packages for printing
            List<tblPackage> packages = new List<tblPackage>();
            foreach (tblPackage package in (ListCollectionView)gridOrders.ItemsSource)
                if (package.Selected)
                    packages.Add(package);

            if (packages.Count() == 0)
            {
                MessageBox.Show("Please select at least one packing list to print.");
                return;
            }

            tblPrintBatch newBatch = new tblPrintBatch();
            newBatch.CreateDate = DateTime.Now;
            _sme.AddTotblPrintBatch(newBatch);
            foreach (tblPackage package in packages)
                package.PrintBatch = newBatch;

            Cursor = Cursors.Wait;
            _sme.SaveChanges();

            // Run the PrintBatchSummary report
            try
            {
                Report rpt = new Report();
                FileStream fs = new FileStream(@".\PrintBatchSummary.rdl", FileMode.Open, FileAccess.Read, FileShare.Read);
                rpt.Load(fs, ".\\");
                fs.Close();
                fs.Dispose();

                rpt.ReportParameters["PrintBatchID"].Value = newBatch.PrintBatchID;

                Rdl.Render.GenericRender render = rpt.Run();
                RdlViewer.ReportViewer viewer1 = new RdlViewer.ReportViewer();
                viewer1.SetReport(render);
                viewer1.PrinterName = (string)cmbPrintSummaryTo.SelectedItem;
                viewer1.Print(false);
            }
            catch (Exception err)
            {
                Cursor = Cursors.Arrow;
                MessageBox.Show("Error printing Summary.\n" + err.Message);
                return;
            }

            // Run the PickList report
            try
            {
                Report rpt = new Report();
                FileStream fs = new FileStream(@".\PickList.rdl", FileMode.Open, FileAccess.Read, FileShare.Read);
                rpt.Load(fs, ".\\");
                fs.Close();
                fs.Dispose();

                rpt.ReportParameters["PrintBatchID"].Value = newBatch.PrintBatchID;

                Rdl.Render.GenericRender render = rpt.Run();
                RdlViewer.ReportViewer viewer1 = new RdlViewer.ReportViewer();
                viewer1.SetReport(render);
                viewer1.PrinterName = (string)cmbPrintPickListTo.SelectedItem;
                viewer1.Print(false);
            }
            catch (Exception err)
            {
                Cursor = Cursors.Arrow;
                MessageBox.Show("Error printing PickList.\n" + err.Message);
                return;
            }

            // Run the PackingSlips report
            try
            {
                Report rpt = new Report();
                string reportPath = ((tblOwner)cmbOwner.SelectedItem).PackingSlipReport;
                if (reportPath == null)
                    reportPath = @".\PackingList.rdl";
                FileStream fs = new FileStream(reportPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                rpt.Load(fs, ".\\");
                fs.Close();
                fs.Dispose();

                rpt.ReportParameters["PrintBatchID"].Value = newBatch.PrintBatchID;

                Rdl.Render.GenericRender render = rpt.Run();
                RdlViewer.ReportViewer viewer1 = new RdlViewer.ReportViewer();
                viewer1.SetReport(render);
                viewer1.PrinterName = (string)cmbPrintPackingSlipsTo.SelectedItem;
                viewer1.Print(false);
            }
            catch( Exception err )
            {
                Cursor = Cursors.Arrow;
                MessageBox.Show("Error printing packing slips.\n" + err.Message);
                return;
            }

            // Mark all of the inventory transactions for the packages in the printed report as having been printed
            foreach (tblPackage package in packages)
                foreach( tblInventoryTransaction inventoryTransaction in package.InventoryTransactions)
                    inventoryTransaction.InventoryTransactionStatusCode = "P";
            _sme.SaveChanges();

            Cursor = Cursors.Arrow;
        }

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            // When the checked value of one or more of the check boxes changes, then set the HasPackagesSelected property accordingly.
            SetValue(HasPackagesSelected, true); 
        }

        private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            // When the checked value of one or more of the check boxes changes, then set the HasPackagesSelected property accordingly.
            ListCollectionView packages = (ListCollectionView)gridOrders.ItemsSource;

            foreach (tblPackage package in packages)
                if (package.Selected)
                    return;
            SetValue(HasPackagesSelected, false);
        }

        private void cmbPrintSummaryTo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            RegistryKey rkey = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\SawikiSoft\OpenSalesManager");
            if (rkey != null)
                rkey.SetValue("PrintSummaryTo", (string)cmbPrintSummaryTo.SelectedItem);
        }

        private void cmbPrintPickListTo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            RegistryKey rkey = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\SawikiSoft\OpenSalesManager");
            if (rkey != null)
                rkey.SetValue("PrintPickListTo", (string)cmbPrintPickListTo.SelectedItem);
        }

        private void cmbPrintPackingSlipsTo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            RegistryKey rkey = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\SawikiSoft\OpenSalesManager");
            if (rkey != null)
                rkey.SetValue("PrintPackingSlipsTo", (string)cmbPrintPackingSlipsTo.SelectedItem);
        }
    }
}
